function [ pop ] = preprocessing( pop, sim_mat, sign )
%PREPROCESSING: Pre-processing the population based on the similarity matrix.
%   pop    : population.
%   sim_mat: similarity matrix.
%   sign   : the sign of the test network(signed or unsigned).

    if isfield(pop, 'net_data')      % judge the type of variable 'pop'
        data = pop.new_data;
        data.label = processing(data.label, sim_mat, sign);
        pop.new_data = data;
    elseif isfield(pop, 'label')     
        pop.label = processing(pop.label, sim_mat, sign);
    else
        error('Undefined data type');
    end     
end

%% 
function label = processing(label, s, sign)
%The function is the core function of preprocessing.
    n = length(label);
    [~, index] = sort(s, 2, 'descend');   
    if strcmpi(sign, 'signed')
        k = sum(s>0, 2);                
    else
        k = ceil( sum(s>0,2)/2 );
    end  
    knn = cell(n,1);
    for i = 1:n
        knn{i} = index(i,1:k(i));       
    end 
    
    iterm = 10;
    while(iterm)
        for j = 1:n
            t_label = label(knn{j});
            label(j) = argmax([t_label label(j)]); 
        end     
        iterm = iterm - 1;        
    end
    label = decode(label);
end

%%
function y = argmax(x)             % noexcept
    tx = unique(x);
    n1 = length(x);
    n2 = length(tx);
    
    if n1 == n2
        tab = ceil(rand * n1);
        y = x(tab);
    else
        c = zeros(1,n2);
        for i=1:n2
            c(i) = length(find(x == tx(i)));
        end
        mtimes = max(c);
        tab = find(c == mtimes);           
        index = ceil(rand*length(tab));     % randomly select an index.
        y = tx(tab(index));
    end        
end
